package com.yx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname ${NAME}
 * @Description TODO:
 * @Date 2021/04/22 19:54
 * @Created by yx
 */
@WebFilter(filterName = "EncodingFilter",value = "/*")
public class EncodingFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        System.out.println("EncodingFilter come in");
        request.setCharacterEncoding("utf-8");
        //放行js,css等文件,避免浏览器报错
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String url=req.getRequestURI();
//        System.out.println("url:" +url);

        if(url.indexOf(".css")>0||url.indexOf(".js")>0||url.indexOf(".png")>0) {
            System.out.println("过滤器");
            chain.doFilter(req, resp);
            return;
        }else{
            response.setContentType("text/html;charset=utf-8");
            chain.doFilter(req, resp);
//            System.out.println("EncodingFilter come out");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
